﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Monk.Solu.Extentions
{
    public static class RazorExtention
    {
        public static MvcHtmlString Button(this HtmlHelper helper, string id, string text = "提交", string type = "button", object htmlAttributes = null)
        {
            TagBuilder builder = new TagBuilder("input");

            builder.IdAttributeDotReplacement = "-";
            builder.GenerateId(id);

            builder.MergeAttributes(new Dictionary<string, string> {
                {"type", type },
                {"value",text }
            });

            builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

            return new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing));
        }

        public static MvcHtmlString SpanFor<TModel, TValue>(this HtmlHelper<TModel> helper, System.Linq.Expressions.Expression<Func<TModel, TValue>> expression, object htmlAttributes = null)
        {
            TagBuilder builder = new TagBuilder("span");

            var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);

            // 获取模型字段的显示文本
            string text = metadata.DisplayName ?? metadata.PropertyName;
            // 获取模型字段的字段名
            string name = ExpressionHelper.GetExpressionText(expression);

            // 获取模型字段的值
            string value;
            ModelState modelState;
            string fullName = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
            if (helper.ViewData.ModelState.TryGetValue(fullName, out modelState) && modelState.Errors.Count > 0)
            {
                builder.AddCssClass(HtmlHelper.ValidationInputCssClassName);
            }
            if (modelState != null && modelState.Value != null)
            {
                value = modelState.Value.AttemptedValue;
            }
            else if (metadata.Model != null)
            {
                value = metadata.Model.ToString();
            }
            else
            {
                value = String.Empty;
            }

            builder.GenerateId(name);

            builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
            builder.InnerHtml = value;

            return new MvcHtmlString(builder.ToString(TagRenderMode.Normal));
        }
    }
}